# -*- coding: utf8 -*-
# $Id :  $



# Copyright 2008-2010, Pascal Fautrero & JCharles
#
# This file is part of PyArchiver.
# 
# PyArchiver is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyArchiver is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyArchiver.  If not, see <http://www.gnu.org/licenses/>.



# Import packages

import wx                        # This module uses the new wx namespace
import sys
import os
import time
import scrolled_window
import locale

# import images                  # For PyEmbeddedImage

_ = wx.GetTranslation            # Define _ or add _ to builtins in your app file

appDir = os.path.split(os.path.abspath(sys.argv[0]))[0]

#---------------------------------------------------------------------------

class My_Printout(wx.Printout):
    def __init__(self, canvas, title):
        wx.Printout.__init__(self, title)
        
        self.canvas = canvas
        title=_(" to the Jacket")
        
    #-----------------------------------------------------------------------
     
    def OnBeginDocument(self, start, end):
        return super(My_Printout, self).OnBeginDocument(start, end)
     
     
    def OnEndDocument(self):
        super(My_Printout, self).OnEndDocument()
     
     
    def OnBeginPrinting(self):
        super(My_Printout, self).OnBeginPrinting()
     
     
    def OnEndPrinting(self):
        super(My_Printout, self).OnEndPrinting()
     
     
    def OnPreparePrinting(self):
        super(My_Printout, self).OnPreparePrinting()
     
     
    def HasPage(self, page):
        if page <= 2:
            return True
        else:
            return False
     
     
    def GetPageInfo(self):
        return (1, 2, 1, 2)
     
     
    def OnPrintPage(self, page):
        dc = self.GetDC()

        #-------------------------------------------------------------------
        
        # One possible method of setting scaling factors...
        maxX = self.canvas.get_width()
        maxY = self.canvas.get_height()
        
        #-------------------------------------------------------------------
     
        # Let's have at least 50 device units margin
        marginX = 180
        marginY = 180
        
        #-------------------------------------------------------------------
        
        # Add the margin to the graphic size
        maxX = maxX + (2 * marginX)
        maxY = maxY + (2 * marginY)
        
        #-------------------------------------------------------------------
        
        # Get the size of the DC in pixels
        (w, h) = dc.GetSizeTuple()
        
        # Calculate a suitable scaling factor
        scaleX = float(w) / maxX
        scaleY = float(h) / maxY
        
        # Use x or y scaling factor, whichever fits on the DC
        actualScale = min(scaleX, scaleY)
        
        # Calculate the position on the DC for centering the graphic
        posX = (w - (self.canvas.get_width() * actualScale)) / 2.0
        posY = (h - (self.canvas.get_height() * actualScale)) / 2.0
        
        # Set the scale and origin
        dc.SetUserScale(actualScale, actualScale)
        dc.SetDeviceOrigin(int(posX), int(posY))
        
        #-------------------------------------------------------------------
        
        self.canvas.do_drawing(dc, True)

        #-------------------------------------------------------------------

        # Timer event
        tm = time.strftime(_("Printing %d %b %Y %a - %Hh%M"))
        
        # Display header - Page number - Timer event
        if wx.Platform == "__WXGTK__":
            dc.SetTextForeground("GRAY")
            dc.SetFont(wx.Font(19, wx.SWISS, wx.NORMAL, wx.BOLD))
            dc.DrawText(_("PyArchiver v2.7 - Jacket"), 0, -120)

            dc.SetTextForeground("BLACK")
            dc.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
            dc.DrawText(_("Page : %d") % page, marginX/2, maxY-marginY)

            dc.SetTextForeground("GRAY")
            dc.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL))
            dc.DrawText(tm, 10, 778)
            
        else:
            dc.SetTextForeground("GRAY")
            dc.SetFont(wx.Font(32, wx.SWISS, wx.NORMAL, wx.BOLD))
            dc.DrawText(_("PyArchiver v2.7 - Jacket"), 0, -150)

            dc.SetTextForeground("BLACK")
            dc.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))
            dc.DrawText(_("Page : %d") % page, marginX/2, maxY-marginY)

            dc.SetTextForeground("GRAY")
            dc.SetFont(wx.Font(16, wx.SWISS, wx.NORMAL, wx.NORMAL))
            dc.DrawText(tm, 10, 764)

        return True
         
#---------------------------------------------------------------------------

class My_PrintPanel(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,
                          title=_("Printing"), size=(780, 500))
        
        #-------------------------------------------------------------------

        iconDir = os.path.join(appDir, "icons")
        frameicon = wx.Icon(os.path.join(iconDir, "printing.ico"), wx.BITMAP_TYPE_ICO)
        # or PyEmbeddedImage
        # frameicon = images.Printing.GetIcon() 
        pfrm.SetIcon(frameicon)
        
        #-------------------------------------------------------------------
        
        panel = wx.Panel(self, -1)
     
        #-------------------------------------------------------------------
        
        self.printData = wx.PrintData()
        self.printData.SetPaperId(wx.PAPER_A4)
        self.printData.SetPrintMode(wx.PRINT_MODE_PRINTER)
        self.printData.SetOrientation(wx.PORTRAIT)
        self.printData.SetQuality(wx.PRINT_QUALITY_HIGH)
        
        #-------------------------------------------------------------------
        
        self.box = wx.BoxSizer(wx.VERTICAL)
        self.canvas = scrolled_window.My_Canvas(panel)
        self.box.Add(self.canvas, 1, wx.GROW)
          
        #-------------------------------------------------------------------
        
        btnOptions = wx.Button(panel, -1, _("&Options..."))
        btnOptions.SetSize(btnOptions.GetBestSize())
        
        btnPreview = wx.Button(panel, -1, _("Pre&view"))
        btnPreview.SetFont(self.normalFont)
        btnPreview.SetSize(btnPreview.GetBestSize())

        btnPrint = wx.Button(panel, -1, _("&Print"))
        btnPrint.SetSize(btnPrint.GetBestSize())
        
        # Bind a button event to an events handler
        self.Bind(wx.EVT_BUTTON, self.on_page_setup, btnOptions)
        self.Bind(wx.EVT_BUTTON, self.on_print_preview, btnPreview)
        self.Bind(wx.EVT_BUTTON, self.on_do_print, btnPrint)

        btnPreview.SetFocus()
        
        #-------------------------------------------------------------------
        
        subbox = wx.BoxSizer(wx.HORIZONTAL)
        
        subbox.Add(btnOptions, 1, wx.GROW | wx.ALL, 2)
        subbox.Add(btnPreview, 1, wx.GROW | wx.ALL, 2)
        subbox.Add(btnPrint, 1, wx.GROW | wx.ALL, 2)
        self.box.Add(subbox, 0, wx.GROW)
        
        #-------------------------------------------------------------------
        
        panel.SetAutoLayout(True)
        panel.SetSizer(self.box)
        self.box.Fit(panel)
        
        #-------------------------------------------------------------------
        
        # An alternate way to make accelerators
        acceltbl = wx.AcceleratorTable([
                (wx.ACCEL_CTRL, ord('O'), btnOptions.GetId()),
                (wx.ACCEL_CTRL, ord('V'), btnPreview.GetId()),
                (wx.ACCEL_CTRL, ord('P'), btnPrint.GetId())
            ])
        self.SetAcceleratorTable(acceltbl)
        
        self.CenterOnParent(wx.BOTH)
        self.Show(True)
        
    #-----------------------------------------------------------------------
     
    def on_page_setup(self, evt):
        psdd = wx.PageSetupDialogData(self.printData)
        
        psdd.SetDefaultMinMargins(True)
        psdd.SetMarginTopLeft((15, 15))
        psdd.SetMarginBottomRight((15, 15))
        
        psdd.CalculatePaperSizeFromId()
        
        dlg = wx.PageSetupDialog(self, psdd)        
        dlg.ShowModal()
        
        # This makes a copy of the wx.PrintData instead of just saving
        # a reference to the one inside the PrintDialogData that will
        # be destroyed when the dialog is destroyed
        self.printData = wx.PrintData(dlg.GetPageSetupData().GetPrintData())
        
        dlg.Destroy()
     
     
    def on_print_preview(self, event):
        title=_(" to the Jacket")
        
        data = wx.PrintDialogData(self.printData)
        
        printout = My_Printout(self.canvas, title)
        printout2 = My_Printout(self.canvas, title)
        self.preview = wx.PrintPreview(printout, printout2, data)
        
        if not self.preview.Ok():
            wx.MessageBox(message=_("There was a problem printing. Perhaps your current printer is not set correctly ?"),
                          caption=_("Printing"), style=wx.OK)
            return
        
        # Initial zoom value
        if wx.Platform == "__WXMAC__":
            self.preview.SetZoom(55)
        else:
            self.preview.SetZoom(40)            
        
        pfrm = wx.PreviewFrame(self.preview, None,
                               _("Preview"))

        iconDir = os.path.join(appDir, "icons")
        frameicon = wx.Icon(os.path.join(iconDir, "printing.ico"), wx.BITMAP_TYPE_ICO)
        # or PyEmbeddedImage
        # frameicon = images.Printing.GetIcon() 
        pfrm.SetIcon(frameicon)
        
        pfrm.Initialize()
        
        pfrm.SetPosition(self.GetPosition())
        pfrm.SetSize(self.GetSize())
        # pfrm.Maximize()
        pfrm.Show(True)
     
     
    def on_do_print(self, event):
        title=_(" to the Jacket")
        pdd = wx.PrintDialogData(self.printData)
        
        pdd.SetToPage(2)
        
        printer = wx.Printer(pdd)
        
        printout = My_Printout(self.canvas, title)
        
        if not printer.Print(self, printout, True):
            wx.MessageBox(message=_("There was a problem printing. Perhaps your current printer is not set correctly ?"),
                          caption=_("Printing"), style=wx.OK)
        else:
            self.printData = wx.PrintData( printer.GetPrintDialogData().GetPrintData() )
        printout.Destroy()


